//
//  DataStructureVC.m
//  New_Runway
//
//  Created by mack on 2018/2/8.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "DataStructureVC.h"
#import "StructureHeader.h"
#import "StructureCell.h"
#import "BrandRankModel.h"
#import "DataCrmCountModel.h"

@interface DataStructureVC ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) UITableView *tableview;
@property (weak, nonatomic) ZJScrollSegmentView *segmentView;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) CGFloat total;
@property (nonatomic, assign) NSInteger isType;
@property (nonatomic, strong) StructureHeader *headerView;
@property (nonatomic, copy) NSString *searchMode;
@property (nonatomic, strong) NSMutableArray *customerArray;

@end

@implementation DataStructureVC
-(NSMutableArray *)dataArray{
    
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
-(NSMutableArray *)customerArray{
    if (!_customerArray) {
        _customerArray = [[NSMutableArray alloc] init];
    }
    return _customerArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.hidden = YES;
    self.view.backgroundColor = kColorWhite();
    [self creatTopView];
    [self initTableview];
    [self initLineView];

    self.isType = 0;
    
    if (self.isSale == YES) {
        self.searchMode = @"CHANNEL_ID";
        [self loadDaySaleData];
    }else{
        [self loadData:[NSString stringWithFormat:@"%@%@",Api,BrandRankApi]];
    }
}

-(void)initLineView{
    kSelfWeak;
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = UIColorHex(0xf5f5f5);
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.top.equalTo(weakSelf.view);
        make.height.mas_equalTo(10);

    }];

}

-(void)creatTopView{
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    kSelfWeak;
    ZJSegmentStyle *style = [[ZJSegmentStyle alloc] init];
    //显示遮盖
    style.showCover = YES;
    style.coverCornerRadius = 5;
    style.coverHeight = 30;
    style.coverBackgroundColor = MAIN_NAV_COLOR();
    style.showLine = NO;
    style.scrollLineColor = MAIN_NAV_COLOR();
    style.titleFont = kFontSize(14);
    style.segmentViewBounces = NO;
    // 颜色渐变
    style.autoAdjustTitlesWidth =  YES;
    style.gradualChangeTitleColor = NO;
    style.normalTitleColor = MAIN_FONT_COLOR();
    style.selectedTitleColor = MAIN_NAV_COLOR();
    if (self.isSale == YES) {
        self.titles = @[@"来源       ", @"销售       "];

    }else{
        self.titles = @[@"品牌       ", @"车系       ",@"车龄       ",@"库龄       "];
    }
    style.titleMargin = 20;
    style.segmentHeight = 40;
    ZJScrollSegmentView *segment = [[ZJScrollSegmentView alloc] initWithFrame:CGRectMake(0, 10,Screen_width, 40) segmentStyle:style delegate:nil titles:self.titles titleDidClick:^(ZJTitleView *titleView, NSInteger index) {
        self.isType = index;
        if (index == 0) {
            if (weakSelf.isSale == YES) {
                weakSelf.searchMode = @"CHANNEL_ID";
                [weakSelf loadDaySaleData];

            }else{
                [weakSelf loadData:[NSString stringWithFormat:@"%@%@",Api,BrandRankApi]];
            }
          
        }else if (index == 1){
            if (weakSelf.isSale == YES) {
                weakSelf.searchMode = @"FOLLOWER_ID";
                [weakSelf loadDaySaleData];

            }else{
                
                [weakSelf loadData:[NSString stringWithFormat:@"%@%@",Api,SeriesRankApi]];
            }
        
          
        }else if (index == 2){
            [weakSelf loadData:[NSString stringWithFormat:@"%@%@",Api,CarAgeRankApi]];
            
        }else if (index == 3){
            [weakSelf loadData:[NSString stringWithFormat:@"%@%@",Api,AgeRankApi]];
         
        }
        
    }];
    
    [self.view addSubview:segment];
    segment.backgroundColor = UIColorHex(0xffffff);
    self.segmentView = segment;
    
}
-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    _tableview.estimatedRowHeight = 0;
    _tableview.estimatedSectionHeaderHeight = 0;
    _tableview.estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    } else {
        
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    self.tableview.backgroundColor = MAIN_COLOR();
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerNib:[UINib nibWithNibName:@"StructureCell" bundle:nil] forCellReuseIdentifier:@"StructureCell"];
    
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_offset(50);
        make.bottom.equalTo(weakSelf.view);
        make.left.right.equalTo(weakSelf.view);
    }];
    
    
    
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.isSale == YES) {
        
        return self.customerArray.count;
    }
    return self.dataArray.count;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    StructureCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StructureCell"];
    if (self.isSale == YES) {
        cell.totalNum = self.crmTotalNum;
        cell.searchMode = self.searchMode;
        DataCrmResult *result = self.customerArray[indexPath.row];
        cell.crmModel = result;
        
    }else{
        cell.totalNum = self.total;
        cell.isType = self.isType;
        BranRankResult *result = self.dataArray[indexPath.row];
        cell.rankModel = result;
    }
 

    return cell;
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    StructureHeader *view = [[[NSBundle mainBundle] loadNibNamed:@"StructureHeader" owner:self options:nil]lastObject];
    view.backgroundColor = UIColorHex(0xf5f5f5);
    view.isSale = self.isSale;
    view.index = self.isType;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 30;
}

-(void)loadData:(NSString *)url{
     NSDictionary *params;
    if (self.isDay == YES) {
      
            params =@{
                    @"marketId":[NRWCarUser sharedUser].marketId,
                    @"startDate":[NRWCarTurnTime timestampSwitchTime:self.currentTime andFormatter:@"yyyy-MM-dd"],
                    @"shopId":self.shopID,
                    @"statisType":self.statisType
                    };
        
    }else{
       
        params =@{
                  @"marketId":[NRWCarUser sharedUser].marketId,
                  @"month":[NRWCarTurnTime timestampSwitchTime:self.currentTime andFormatter:@"yyyy-MM"],
                  @"shopId":self.shopID,
                  @"statisType":self.statisType
                  
                  };
    }
    
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        [self.dataArray removeAllObjects];
        self.total = 0;
       BrandRankModel *rankModel = [BrandRankModel mj_objectWithKeyValues:response];
        for (NSDictionary *dic in rankModel.result) {
            BranRankResult *result = [BranRankResult mj_objectWithKeyValues:dic];
            [self.dataArray addObject:result];
            self.total += result.storageNum;
        }
        [self.tableview reloadData];
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
    
}

-(void)loadDaySaleData{
    NSString *url =[NSString stringWithFormat:@"%@%@",CRMContextApi,DataCrmValueApi];
   NSDictionary *params =@{
              @"searchMode":self.searchMode,
              @"queryDate":[NRWCarTurnTime timestampSwitchTime:self.currentTime andFormatter:@"yyyy-MM-dd"],
              @"shopId":self.shopID,
              @"searchType":self.searchType,
              @"followState":@(self.followState)
              };
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        DataCrmCountModel *model = [DataCrmCountModel mj_objectWithKeyValues:response];
        [self.customerArray removeAllObjects];
        if (model.code == 1) {
            
            for (NSDictionary *dic in model.result) {
                DataCrmResult *crmResult = [DataCrmResult mj_objectWithKeyValues:dic];
                [self.customerArray addObject:crmResult];
            }
             [self.tableview reloadData];
        }
      
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
